package com.itwang.ipwatchdog;

import com.itwang.common.Logger;
import com.itwang.common.PropertiesUtil;
import com.itwang.thread.IpWatchThread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Application {
	
	
	static ThreadPoolExecutor threadPoolExecutor;
	static {
		//创建线程池
		threadPoolExecutor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
	}
	
	public static void run() {
		/***
		 * 创建一个线程
		 * 线程读取系统ip并且和保存在磁盘的ip信息进行比对.
		 * 如果ip变动则更新磁盘ip并且向目标邮箱发送最新的ip地址
		 * 线程休眠
		 */
		IpWatchThread ipWatchingThread = new IpWatchThread();
		
		Long threadCheckTime = Long.valueOf(PropertiesUtil.getKey("threadCheckTime"));
		Integer tryTimes = Integer.valueOf(PropertiesUtil.getKey("threadTryTimes"));
		
		while (true){
			if (threadPoolExecutor.getActiveCount() < 1){
				//等于-1则不做检测
				if (tryTimes != -1){
					if(tryTimes == 0){
						//一旦发现tryTimes等于0,则直接停止守护进程
						Logger.keyInfo("进程池关闭");
						threadPoolExecutor.shutdown();
						return;
					}
					if(tryTimes > 0){
						tryTimes--;
					}
				}
				threadPoolExecutor.execute(ipWatchingThread);
				Logger.info("IP看门狗创建了一个IP监控线程");
			}
			//每固定时间检查一次线程是否正常,如果不正常则执行一个新线程
			try {
				Thread.sleep(threadCheckTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	}
}
